package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysOrgPersonModel;
import com.ruoyi.system.domain.UserModel;
import com.ruoyi.system.mapper.SysOrgPersonMapper;
import com.ruoyi.system.service.SysOrgPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hnb
 * @Date 2024/11/29
 * @Description
 **/
@Service
public class SysOrgPersonServiceImpl implements SysOrgPersonService {
    @Autowired
    private SysOrgPersonMapper sysOrgPersonMapper;

    @Override
    public List<SysOrgPersonModel> selectEkpList() {
        return sysOrgPersonMapper.selectEkpList();
    }

    @Override
    public int updateEkpPerson() throws Exception {
        //获取ekp所有用户
        List<SysOrgPersonModel> sysOrgPersonModels = selectEkpList();
        //获取金蝶用户
        List<UserModel> resultList = getJDPerson();
        Map<String, Object> map = new HashMap<>();
        for (UserModel userModel : resultList) {
            if (!map.containsKey(userModel.getFName())) {
                map.put(userModel.getFName(), userModel);
            }
        }
        for (SysOrgPersonModel sysOrgPersonModel : sysOrgPersonModels) {
            if (map.containsKey(sysOrgPersonModel.getFdName())) {
                sysOrgPersonModel.setFdNo(((UserModel)map.get(sysOrgPersonModel.getFdName())).getFNumber());
                sysOrgPersonModel.setFdShiyongzuzhi(((UserModel)map.get(sysOrgPersonModel.getFdName())).getShiyongzuzhi());
                sysOrgPersonMapper.updatePerson(sysOrgPersonModel);
            }
        }
        return 1;
    }

    @Override
    public int updateJdPerson() throws Exception {
        //获取ekp所有用户
        List<SysOrgPersonModel> sysOrgPersonModels = selectEkpList();
        //获取金蝶用户
        List<UserModel> resultList = getJDPerson();
        Map<String, Object> map = new HashMap<>();
        for (UserModel userModel : resultList) {
            if (!map.containsKey(userModel.getFNumber())) {
                map.put(userModel.getFNumber(), userModel);
            } else {
                UserModel userModel1 = (UserModel) map.get(userModel.getFNumber());
                userModel1.setCount(2);
                map.remove(userModel.getFNumber());
                map.put(userModel1.getFNumber(), userModel1);
            }
        }
        for (SysOrgPersonModel sysOrgPersonModel : sysOrgPersonModels) {
            //如果人员编码
            if (map.containsKey(sysOrgPersonModel.getFdNo()) && (!sysOrgPersonModel.getFdName().equals(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getFName())
            ||(StringUtils.isNotEmpty(sysOrgPersonModel.getFdDeptNo())&&!sysOrgPersonModel.getFdDeptNo().equals(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getFdDeptNo()))
            ||(StringUtils.isNotEmpty(sysOrgPersonModel.getFdShiyongzuzhi())&&!sysOrgPersonModel.getFdShiyongzuzhi().equals(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getShiyongzuzhi())))) {

                sysOrgPersonModel.setFdjdId(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getFdId());
                //在金蝶人员有多个部门则不更新部门
                if (!ObjectUtils.isEmpty(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getCount())
                        &&((UserModel) map.get(sysOrgPersonModel.getFdNo())).getCount() == 2) {
                    sysOrgPersonModel.setFdDeptNo(null);
                }
                updatePerson(sysOrgPersonModel);
                map.remove(sysOrgPersonModel.getFdNo());

            } else if (StringUtils.isEmpty(sysOrgPersonModel.getFdNo()) || !map.containsKey(sysOrgPersonModel.getFdNo())) {//在金蝶未查到编码的人员则新增
                String number = savePerson(sysOrgPersonModel);
                sysOrgPersonModel.setFdNo(number);
                //更新编号
                sysOrgPersonMapper.updatePerson(sysOrgPersonModel);
            } else if (map.containsKey(sysOrgPersonModel.getFdNo()) && sysOrgPersonModel.getFdName().equals(((UserModel) map.get(sysOrgPersonModel.getFdNo())).getFName())) {
                map.remove(sysOrgPersonModel.getFdNo());
            }
        }
        //禁用金蝶在ekp没有的人员
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            SysOrgPersonModel sysOrgPersonModel = new SysOrgPersonModel();
            sysOrgPersonModel.setFdNo(entry.getKey());
            disAblePerson(sysOrgPersonModel);
        }
        return 0;
    }

    /**
     * 获取金蝶人员
     *
     * @return
     * @throws Exception
     */
    private List<UserModel> getJDPerson() throws Exception {
        K3CloudApi client = new K3CloudApi();
        //请求参数，要求为json字符串
        String jsonData = "{\n" +
                "    \"FormId\": \"BD_Empinfo\",\n" +
                "    \"FieldKeys\": \"FName,Fnumber,FBaseProperty3,FID,FUseOrgId.FNumber,FPostDept.FNumber,FMobile,FForbidStatus,FDocumentStatus,FCreateOrgId\",\n" +
//                "    \"FilterString\": [{\"FieldName\":\"FForbidStatus\",\"Compare\":\"67\",\"Value\":\"A\",\"Left\":\"\",\"Right\":\"\",\"Logic\":\"0\"}],\n" +
                "    \"FilterString\": \"FForbidStatus='A'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 0,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        List<UserModel> resultList = new ArrayList<>();

        //调用接口
        List<List<Object>> lists = client.executeBillQuery(jsonData);
        System.out.println("接口返回结果: " + String.valueOf(lists));
        for (List<Object> list : lists) {
            UserModel userModel = new UserModel();
            userModel.setFName((String) list.get(0));
            userModel.setFNumber((String) list.get(1));
            userModel.setFBaseProperty3((String) list.get(2));
            userModel.setFdId((Integer) list.get(3));
            userModel.setShiyongzuzhi((String) list.get(4));
            userModel.setFdDeptNo((String) list.get(5));
            resultList.add(userModel);
        }

        return resultList;
    }

    /**
     * 保存金蝶人员
     *
     * @param sysOrgPersonModel
     * @return
     */
    private String savePerson(SysOrgPersonModel sysOrgPersonModel) {
        K3CloudApi client = new K3CloudApi();
        //请求参数，要求为json字符串
        String jsonData = personParam(sysOrgPersonModel);
        String number = null;
        try {
            //业务对象标识
            String formId = "BD_Empinfo";
            //调用接口
            String resultJson = client.save(formId, jsonData);
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                System.out.printf("接口返回结果: %s%n", gson.toJson(repoRet.getResult()));
                number = repoRet.getResult().getResponseStatus().getSuccessEntitys().get(0).getNumber();
            } else {
                System.out.printf("接口返回结果: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }
            if (repoRet.getResult().getResponseStatus().isIsSuccess() && StringUtils.isNotEmpty(repoRet.getResult().getResponseStatus().getSuccessEntitys().get(0).getId())) {
                //请求参数，要求为json字符串
                String jsonData1 = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" +
                        repoRet.getResult().getId() +
                        "\",\"SelectedPostId\":0,\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";

                //调用接口
                String resultJson1 = client.submit(formId, jsonData1);
                //对返回结果进行解析和校验
                RepoRet repoRet1 = gson.fromJson(resultJson1, RepoRet.class);
                if (repoRet1.getResult().getResponseStatus().isIsSuccess()) {
                    System.out.printf("接口提交返回结果: %s%n", gson.toJson(repoRet.getResult()));
                } else {
                    System.out.printf("接口提交返回结果: %s%n", gson.toJson(repoRet.getResult().getResponseStatus()));
                    return repoRet1.getResult().getResponseStatus().getErrors().get(0).getMessage();
                }
                if (repoRet1.getResult().getResponseStatus().isIsSuccess() && StringUtils.isNotEmpty(repoRet1.getResult().getResponseStatus().getSuccessEntitys().get(0).getId())) {
                    String jsonData2 = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" +
                            repoRet.getResult().getId() +
                            "\",\"InterationFlags\":\"\",\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"true\",\"IgnoreInterationFlag\":\"\",\"UseBatControlTimes\":\"false\"}";
                    //调用接口
                    String resultJson2 = client.audit(formId, jsonData2);
                    //对返回结果进行解析和校验
                    RepoRet repoRet2 = gson.fromJson(resultJson2, RepoRet.class);
                    if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                        System.out.printf("接口返回结果: %s%n", gson.toJson(repoRet2.getResult()));
                    } else {
                        System.out.println("接口返回结果: " + gson.toJson(repoRet2.getResult().getResponseStatus()));
                    }
                }
            }
        } catch (Exception e) {
            System.out.printf(e.getMessage());
        }
        return number;
    }

    /**
     * 处理参数
     *
     * @param sysOrgPersonModel
     * @return
     */
    private String personParam(SysOrgPersonModel sysOrgPersonModel) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> modelMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(sysOrgPersonModel.getFdjdId())) {
            modelMap.put("FID", sysOrgPersonModel.getFdjdId());
        }
        if (StringUtils.isNotEmpty(sysOrgPersonModel.getFdName())) {
            modelMap.put("FName", sysOrgPersonModel.getFdName());
        }
        if (StringUtils.isNotEmpty(sysOrgPersonModel.getFdNo())) {
            modelMap.put("FStaffNumber", sysOrgPersonModel.getFdNo());
        }
        if(StringUtils.isNotEmpty(sysOrgPersonModel.getFdShiyongzuzhi())) {
            Map<String, String> fUseOrgId = new HashMap<String, String>() {{
                put("FNumber", sysOrgPersonModel.getFdShiyongzuzhi());
            }};
            modelMap.put("FUseOrgId", fUseOrgId);
        }
        if (StringUtils.isNotEmpty(sysOrgPersonModel.getFdDeptNo())) {
            Map<String, Object> fPostEntity = new HashMap<String, Object>() {{
                HashMap<String, String> fPostDept = new HashMap<String, String>() {{
                    put("FNumber", sysOrgPersonModel.getFdDeptNo());
                }};
                put("FPostDept", fPostDept);
            }};
            modelMap.put("fPostEntity", fPostEntity);
        }
        map.put("Model", modelMap);
        return JSON.toJSONString(map);
    }

    /**
     * 更新金蝶人员
     *
     * @param sysOrgPersonModel
     * @return
     */

    private String updatePerson(SysOrgPersonModel sysOrgPersonModel) {
        K3CloudApi client = new K3CloudApi();
        //请求参数，要求为json字符串
        String jsonData = personParam(sysOrgPersonModel);
        try {
            //业务对象标识
            String formId = "BD_Empinfo";
            //调用接口
            String resultJson = client.save(formId, jsonData);
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                System.out.printf("接口返回结果: %s%n", gson.toJson(repoRet.getResult()));
            } else {
                System.out.printf("接口返回结果: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        } catch (Exception e) {
            System.out.printf(e.getMessage());
        }
        return null;
    }

    /**
     * 禁用金蝶人员
     *
     * @param sysOrgPersonModel
     * @return
     */
    private String disAblePerson(SysOrgPersonModel sysOrgPersonModel) {
        K3CloudApi client = new K3CloudApi();
        //请求参数，要求为json字符串
        Map<String, String> map = new HashMap<>();
        map.put("Numbers", sysOrgPersonModel.getFdNo());
        String jsonData = JSON.toJSONString(map);
//        String jsonData = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"\",\"PkEntryIds\":[],\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
        try {
            //业务对象标识
            String formId = "BD_Empinfo";
            //操作接口编码
            String operateNumber = "Forbid";
            //调用接口
            String resultJson = client.excuteOperation(formId, operateNumber, jsonData);

            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                System.out.printf("接口返回结果: %s%n", gson.toJson(repoRet.getResult()));
            } else {
                System.out.printf("接口返回结果: " + gson.toJson(repoRet.getResult().getResponseStatus()));
            }
        } catch (Exception e) {
            System.out.printf(e.getMessage());
        }
        return null;
    }
}
